﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Documents;
using PSE.Deployment.SetupBase;
using PSE.Deployment.SetupBase.Parameter.Enums;
using PSE.Deployment.Util;
using Sinacor.Deployment.Setup.DataAccess;
using Sinacor.Deployment.Setup.Main;

namespace Sinacor.Deployment.Setup.UI
{
    /// <summary>
    /// Interaction logic for BancoDadosPassoB.xaml
    /// </summary>
    public partial class ServiceCompanyChecking : BaseDataBaseWizardWindow
    {
        #region Propriedades
        public Parameter.DataBaseConnection ConnectionInfo { get; set; }

        public List<CompanyVersion> CompaniesVersions
        {
            get { return (List<CompanyVersion>)GetValue(CompaniesVersionsProperty); }
            set { SetValue(CompaniesVersionsProperty, value); }
        }

        // Using a DependencyProperty as the backing store for CompaniesVersions.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty CompaniesVersionsProperty =
            DependencyProperty.Register("CompaniesVersions", typeof(List<CompanyVersion>), typeof(ServiceCompanyChecking), new UIPropertyMetadata());
        #endregion

        #region Construtor
        public ServiceCompanyChecking()
        {
            this.InitializeComponent();

            this.CompaniesVersions = new List<CompanyVersion>();

            this.DataContext = this;
            this.AllowNext = true;

            AddCompanies();

        }
        #endregion

        #region Métodos para Listar as Compatibilidade das Empresas 
        private void AddCompanies()
        {
            this.CompaniesVersions.Clear();

            foreach (Configuration.VersionInfo versionInfo in SetupMainFactory.GetInstance<SinacorMain>().Configuration.DataBase.Versions)
            {
                using (OracleDataBase db = new OracleDataBase(SetupMainFactory.GetInstance<SinacorMain>().Parameter.DataBase.ConnectionInfo.User, EncryptDecrypt.Decrypt(SetupMainFactory.GetInstance<SinacorMain>().Parameter.DataBase.ConnectionInfo.Password), SetupMainFactory.GetInstance<SinacorMain>().Parameter.DataBase.ConnectionInfo.TNSName, SetupMainFactory.GetInstance<SinacorMain>().Parameter.DataBase.ConnectionInfo.IsEncrypted))
                {
                    StringBuilder sqlCommand = new StringBuilder();

                    sqlCommand.Append("SELECT E.CD_EMPRESA, E.NM_EMPRESA, E.CD_USUA_ORAC, I.VS_SIST_INST FROM TGEEMPR E LEFT JOIN TGESINST I ON E.CD_EMPRESA = I.CD_EMPRESA and I.CD_SISTEMA = :CodSistema");
                    List<DataBaseParameter> dataBaseParameter = new List<DataBaseParameter>();
                    DataBaseParameter paramSistema = new DataBaseParameter("CodSistema", versionInfo.Module.Id.ToUpper());
                    dataBaseParameter.Add(paramSistema);

                    using (IDataReader dr = db.ExecuteReader(sqlCommand.ToString(), dataBaseParameter))
                    {
                        while (dr.Read())
                        {
                            CompanyVersion version = new CompanyVersion();

                            version.Company.Id = dr.GetInt32(0);
                            version.Company.Login = dr.GetString(2);
                            version.Company.Name = dr.GetString(2) + " ( " + dr.GetString(1) + " )";

                            version.Company.DataBaseVersion = dr[3].ToString();

                            version.Company.Module.Id = versionInfo.Module.Id;
                            version.Company.Module.Name = versionInfo.Module.Name;
                            version.SetupVersions = SetupMainFactory.GetInstance<SinacorMain>().Configuration.DataBase.Versions.Find(v => v.Module.Id == versionInfo.Module.Id).Versions;
                            version.ExtendedSetupVersions = GetExtendedSetupVersion(version.SetupVersions);

                            if (version.SetupVersions.Contains(version.Company.DataBaseVersion))
                            {
                                version.Status = PrerequisitesStatus.Ok;
                            }
                            else
                            {
                                version.Status = PrerequisitesStatus.NotOk;
                            }


                            version.ToolTipMessage = GetCompanyToolTipMessage(version.Status);
                            
                            if (!string.IsNullOrEmpty(version.Company.DataBaseVersion))
                                this.CompaniesVersions.Add(version);

                        }
                    }
                }
            }

            this.CompaniesVersions = this.CompaniesVersions.OrderBy(c => c.Company.Name).ToList(); 
                
        }

        private string GetCompanyToolTipMessage(PrerequisitesStatus status)
        {
            string toolTipMessage = String.Empty;

            switch (status)
            {
                case PrerequisitesStatus.Ok:
                    toolTipMessage = "Versões compatíveis";
                    break;
                case PrerequisitesStatus.NotOk:
                    toolTipMessage = "Versões incompatíveis. " + Environment.NewLine + "Os serviços a serem instalados não funcionarão para esta empresa.";
                    break;
            }

            return toolTipMessage;
        }

        private string GetExtendedSetupVersion(List<string> Versions)
        {
            string extendedSetupVersion = String.Empty;

            foreach (string version in Versions)
            {
                extendedSetupVersion += version + ", ";
            }

            if (extendedSetupVersion != string.Empty)
                extendedSetupVersion = extendedSetupVersion.Substring(0, extendedSetupVersion.Length - 2);

            return extendedSetupVersion;
        }
        #endregion
    }
}
